<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  
  <title>golang文本编码处理 | haijd</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
  
  <meta name="keywords" content="Golang入门" />
  
  
  
  
  <meta name="description" content="strings库常见例子strings.Contains()包含123456789import(    &quot;fmt&quot;    &quot;strings&quot;)func main()&amp;#123;    str := &quot;hello world&quot;    fmt.Println(strings.Contains(str,&quot;hello&quot;))      //输出 true    fmt.Println(strings.Con">
<meta name="keywords" content="Golang入门">
<meta property="og:type" content="article">
<meta property="og:title" content="Golang文本编码处理">
<meta property="og:url" content="http://www.hais2.com/2017/09/05/Golang文本编码处理/index.html">
<meta property="og:site_name" content="haijd">
<meta property="og:description" content="strings库常见例子strings.Contains()包含123456789import(    &quot;fmt&quot;    &quot;strings&quot;)func main()&amp;#123;    str := &quot;hello world&quot;    fmt.Println(strings.Contains(str,&quot;hello&quot;))      //输出 true    fmt.Println(strings.Con">
<meta property="og:locale" content="default">
<meta property="og:image" content="http://ww1.sinaimg.cn/large/c55a7aeely1ficnszlhh9j20go098jrl.jpg">
<meta property="og:updated_time" content="2017-09-06T15:10:56.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Golang文本编码处理">
<meta name="twitter:description" content="strings库常见例子strings.Contains()包含123456789import(    &quot;fmt&quot;    &quot;strings&quot;)func main()&amp;#123;    str := &quot;hello world&quot;    fmt.Println(strings.Contains(str,&quot;hello&quot;))      //输出 true    fmt.Println(strings.Con">
<meta name="twitter:image" content="http://ww1.sinaimg.cn/large/c55a7aeely1ficnszlhh9j20go098jrl.jpg">
  
    <link rel="alternate" href="/atom.xml" title="haijd" type="application/atom+xml">
  
  <link rel="icon" href="/css/images/favicon.ico">
  
    <link href="//fonts.googleapis.com/css?family=Source+Code+Pro" rel="stylesheet" type="text/css">
  
  <link href="https://fonts.googleapis.com/css?family=Open+Sans|Montserrat:700" rel="stylesheet" type="text/css">
  <link href="https://fonts.googleapis.com/css?family=Roboto:400,300,300italic,400italic" rel="stylesheet" type="text/css">
  <link href="//cdn.bootcss.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet">
  <style type="text/css">
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/9749f0/00000000000000000001008f/27/l?subset_id=2&fvd=n5) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/90cf9f/000000000000000000010091/27/l?subset_id=2&fvd=n7) format("woff2");font-weight:500;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/8a5494/000000000000000000013365/27/l?subset_id=2&fvd=n4) format("woff2");font-weight:lighter;font-style:normal;}
    @font-face{font-family:futura-pt;src:url(https://use.typekit.net/af/d337d8/000000000000000000010095/27/l?subset_id=2&fvd=i4) format("woff2");font-weight:400;font-style:italic;}</style>
    
  <link rel="stylesheet" id="athemes-headings-fonts-css" href="//fonts.googleapis.com/css?family=Yanone+Kaffeesatz%3A200%2C300%2C400%2C700&amp;ver=4.6.1" type="text/css" media="all">
  <link rel="stylesheet" href="/css/style.css">

  <script src="/js/jquery-3.1.1.min.js"></script>

  <!-- Bootstrap core CSS -->
  <link rel="stylesheet" href="/css/bootstrap.css" >
  <link rel="stylesheet" href="/css/hiero.css" >
  <link rel="stylesheet" href="/css/glyphs.css" >
  
    <link rel="stylesheet" href="/css/vdonate.css" >
  

</head>

<script>
var themeMenus = {};

  themeMenus["/"] = "Home"; 

  themeMenus["/archives"] = "Archives"; 

  themeMenus["/categories"] = "Categories"; 

  themeMenus["/tags"] = "Tags"; 

  themeMenus["/about"] = "About"; 

</script>


  <body data-spy="scroll" data-target="#toc" data-offset="50">


  <header id="allheader" class="site-header" role="banner">
  <div class="clearfix container">
      <div class="site-branding">

          <h1 class="site-title">
            
              <a href="/" title="haijd" rel="home"> haijd </a>
            
          </h1>

          
            <div class="site-description">Stay Hungry,Stay Foolish</div>
          
            
          <nav id="main-navigation" class="main-navigation" role="navigation">
            <a class="nav-open">Menu</a>
            <a class="nav-close">Close</a>
            <div class="clearfix sf-menu">

              <ul id="main-nav" class="nmenu sf-js-enabled">
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/">Home</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/archives">Archives</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/categories">Categories</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/tags">Tags</a> </li>
                    
                      <li class="menu-item menu-item-type-custom menu-item-object-custom menu-item-home menu-item-1663"> <a class="" href="/about">About</a> </li>
                    
              </ul>
            </div>
          </nav>


      </div>
  </div>
</header>




  <div id="container">
    <div id="wrap">
            
      <div id="content" class="outer">
        
          <section id="main" style="float:none;"><article id="post-Golang文本编码处理" style="width: 66%; float:left;" class="article article-type-post" itemscope itemprop="blogPost" >
  <div id="articleInner" class="clearfix post-1016 post type-post status-publish format-standard has-post-thumbnail hentry category-template-2 category-uncategorized tag-codex tag-edge-case tag-featured-image tag-image tag-template">
    
<div class="article-gallery">
  <div class="article-gallery-photos">
    
      <a class="article-gallery-img fancybox" href="http://ww1.sinaimg.cn/large/c55a7aeely1ficnszlhh9j20go098jrl.jpg" rel="gallery_cjie4nafi003b3swag1j1evlx">
        <img src="http://ww1.sinaimg.cn/large/c55a7aeely1ficnszlhh9j20go098jrl.jpg" itemprop="image">
      </a>
    
  </div>
</div>

    
      <header class="article-header">
        
  
    <h1 class="thumb" class="article-title" itemprop="name">
      Golang文本编码处理
    </h1>
  

      </header>
    
    <div class="article-meta">
      
	Posted on <a href="/2017/09/05/Golang文本编码处理/" class="article-date">
	  <time datetime="2017-09-05T14:43:02.000Z" itemprop="datePublished">September 5, 2017</time>
	</a>

      
	<span id="busuanzi_container_page_pv">
	  本文总阅读量<span id="busuanzi_value_page_pv"></span>次
	</span>

    </div>
    <div class="article-entry" itemprop="articleBody">
      
        <h2 id="strings库常见例子"><a href="#strings库常见例子" class="headerlink" title="strings库常见例子"></a>strings库常见例子</h2><h3 id="strings-Contains-包含"><a href="#strings-Contains-包含" class="headerlink" title="strings.Contains()包含"></a><code>strings.Contains()</code>包含</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strings"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    str := <span class="string">"hello world"</span></span><br><span class="line">    fmt.Println(strings.Contains(str,<span class="string">"hello"</span>))      <span class="comment">//输出 true</span></span><br><span class="line">    fmt.Println(strings.Contains(str,<span class="string">"?"</span>))      <span class="comment">//输出  false</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<h3 id="strings-Index-索引"><a href="#strings-Index-索引" class="headerlink" title="strings.Index()索引"></a><code>strings.Index()</code>索引</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strings"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    str := <span class="string">"hello world"</span></span><br><span class="line">    fmt.Println(strings.Index(str,<span class="string">"w"</span>))      <span class="comment">//输出 6</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="strings-Split-切割"><a href="#strings-Split-切割" class="headerlink" title="strings.Split()切割"></a><code>strings.Split()</code>切割</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strings"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    str := <span class="string">"hello,world"</span></span><br><span class="line">    fmt.Println(strings.Split(str,<span class="string">","</span>))      <span class="comment">//输出 [hello world]</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="strings-Join-合并"><a href="#strings-Join-合并" class="headerlink" title="strings.Join()合并"></a><code>strings.Join()</code>合并</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strings"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    str := []<span class="keyword">string</span>&#123;<span class="string">"hello"</span>,<span class="string">"world"</span>&#125;</span><br><span class="line">    fmt.Println(strings.Join(str,<span class="string">","</span>))      <span class="comment">//输出 hello,world</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="strings-HasPrefix-strings-HasSuffix-是否包含前、后缀"><a href="#strings-HasPrefix-strings-HasSuffix-是否包含前、后缀" class="headerlink" title="strings.HasPrefix() strings.HasSuffix()是否包含前、后缀"></a><code>strings.HasPrefix() strings.HasSuffix()</code>是否包含前、后缀</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strings"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    str := <span class="string">"hello,world"</span></span><br><span class="line">    fmt.Println(strings.HasPrefix(str,<span class="string">"he"</span>))      <span class="comment">//输出 true</span></span><br><span class="line">    fmt.Println(strings.HasSuffix(str,<span class="string">"ld"</span>))      <span class="comment">//输出 true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="strconv库常用操作"><a href="#strconv库常用操作" class="headerlink" title="strconv库常用操作"></a><code>strconv</code>库常用操作</h2><h3 id="Itoa数字转字符串"><a href="#Itoa数字转字符串" class="headerlink" title="Itoa数字转字符串"></a><code>Itoa</code>数字转字符串</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strconv"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    fmt.Println(strconv.Itoa(<span class="number">10</span>))  <span class="comment">//输出 10</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>Itoa的内部实现:<br>可以看到是直接调用<code>FormatInt</code>函函数进行格式化的</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Itoa is shorthand for FormatInt(int64(i), 10).</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Itoa</span><span class="params">(i <span class="keyword">int</span>)</span> <span class="title">string</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> FormatInt(<span class="keyword">int64</span>(i), <span class="number">10</span>)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Atoi字符串转数字"><a href="#Atoi字符串转数字" class="headerlink" title="Atoi字符串转数字"></a><code>Atoi</code>字符串转数字</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strconv"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    fmt.Println(strconv.Atoi(<span class="string">"10"</span>))  <span class="comment">//输出 10 &lt;nil&gt;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li>Atoi的内部实现:<br>内部调用了<code>ParseInt</code>函数进行转换，失败会将异常返回，所以传入的字符串必须是符合转换要求的</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Atoi returns the result of ParseInt(s, 10, 0) converted to type int.</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">Atoi</span><span class="params">(s <span class="keyword">string</span>)</span> <span class="params">(<span class="keyword">int</span>, error)</span></span> &#123;</span><br><span class="line">	<span class="keyword">const</span> fnAtoi = <span class="string">"Atoi"</span></span><br><span class="line">	i64, err := ParseInt(s, <span class="number">10</span>, <span class="number">0</span>)</span><br><span class="line">	<span class="keyword">if</span> nerr, ok := err.(*NumError); ok &#123;</span><br><span class="line">		nerr.Func = fnAtoi</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">int</span>(i64), err</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="ParseBool字符串转bool类型"><a href="#ParseBool字符串转bool类型" class="headerlink" title="ParseBool字符串转bool类型"></a><code>ParseBool</code>字符串转bool类型</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strconv"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    fmt.Println(strconv.ParseBool(<span class="string">"true"</span>))  <span class="comment">//输出 true &lt;nil&gt;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>ParseBool</code>的内部实现：<br>从内部实现可以看到这个函数需要的参数要求</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ParseBool returns the boolean value represented by the string.</span></span><br><span class="line"><span class="comment">// It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False.</span></span><br><span class="line"><span class="comment">// Any other value returns an error.</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">ParseBool</span><span class="params">(str <span class="keyword">string</span>)</span> <span class="params">(<span class="keyword">bool</span>, error)</span></span> &#123;</span><br><span class="line">	<span class="keyword">switch</span> str &#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="string">"1"</span>, <span class="string">"t"</span>, <span class="string">"T"</span>, <span class="string">"true"</span>, <span class="string">"TRUE"</span>, <span class="string">"True"</span>:</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">true</span>, <span class="literal">nil</span></span><br><span class="line">	<span class="keyword">case</span> <span class="string">"0"</span>, <span class="string">"f"</span>, <span class="string">"F"</span>, <span class="string">"false"</span>, <span class="string">"FALSE"</span>, <span class="string">"False"</span>:</span><br><span class="line">		<span class="keyword">return</span> <span class="literal">false</span>, <span class="literal">nil</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="literal">false</span>, syntaxError(<span class="string">"ParseBool"</span>, str)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="ParseFloat字符串转浮点数"><a href="#ParseFloat字符串转浮点数" class="headerlink" title="ParseFloat字符串转浮点数"></a><code>ParseFloat</code>字符串转浮点数</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strconv"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    fmt.Println(strconv.ParseFloat(<span class="string">"1.11"</span>,<span class="number">64</span>))  <span class="comment">//输出 1.11 &lt;nil&gt;</span></span><br><span class="line">    fmt.Println(strconv.ParseFloat(<span class="string">"1.11"</span>,<span class="number">32</span>))  <span class="comment">//输出 1.1100000143051147 &lt;nil&gt;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>ParseFloat</code>的内部实现：<br>可以看到内部最终是把转换后的浮点数放到float64类型中返回的</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// ParseFloat converts the string s to a floating-point number</span></span><br><span class="line"><span class="comment">// with the precision specified by bitSize: 32 for float32, or 64 for float64.</span></span><br><span class="line"><span class="comment">// When bitSize=32, the result still has type float64, but it will be</span></span><br><span class="line"><span class="comment">// convertible to float32 without changing its value.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// If s is well-formed and near a valid floating point number,</span></span><br><span class="line"><span class="comment">// ParseFloat returns the nearest floating point number rounded</span></span><br><span class="line"><span class="comment">// using IEEE754 unbiased rounding.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// The errors that ParseFloat returns have concrete type *NumError</span></span><br><span class="line"><span class="comment">// and include err.Num = s.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// If s is not syntactically well-formed, ParseFloat returns err.Err = ErrSyntax.</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// If s is syntactically well-formed but is more than 1/2 ULP</span></span><br><span class="line"><span class="comment">// away from the largest floating point number of the given size,</span></span><br><span class="line"><span class="comment">// ParseFloat returns f = ±Inf, err.Err = ErrRange.</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">ParseFloat</span><span class="params">(s <span class="keyword">string</span>, bitSize <span class="keyword">int</span>)</span> <span class="params">(<span class="keyword">float64</span>, error)</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> bitSize == <span class="number">32</span> &#123;</span><br><span class="line">		f, err := atof32(s)</span><br><span class="line">		<span class="keyword">return</span> <span class="keyword">float64</span>(f), err</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> atof64(s)</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="Format-格式化"><a href="#Format-格式化" class="headerlink" title="Format...格式化"></a><code>Format...</code>格式化</h3><figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span>(</span><br><span class="line">    <span class="string">"fmt"</span></span><br><span class="line">    <span class="string">"strconv"</span></span><br><span class="line">)</span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">main</span><span class="params">()</span></span>&#123;</span><br><span class="line">    fmt.Println(strconv.FormatBool(<span class="literal">true</span>)) <span class="comment">//输出 true(字符串)</span></span><br><span class="line">	fmt.Println(strconv.FormatFloat(<span class="number">1.123</span>, <span class="string">'e'</span>, <span class="number">2</span>, <span class="number">32</span>))  <span class="comment">//输出 1.12e+00(字符串)</span></span><br><span class="line">	fmt.Println(strconv.FormatInt(<span class="number">222</span>,<span class="number">2</span>))   <span class="comment">//输出 11011110(字符串)</span></span><br><span class="line"> 	fmt.Println(strconv.FormatUint(<span class="number">123</span>,<span class="number">10</span>))  <span class="comment">//输出 123(字符串)</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>FormatBool</code>内部实现：<br>内部实现比较简单，直接if判断返回相应的字符串</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// FormatBool returns "true" or "false" according to the value of b</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">FormatBool</span><span class="params">(b <span class="keyword">bool</span>)</span> <span class="title">string</span></span> &#123;</span><br><span class="line">	<span class="keyword">if</span> b &#123;</span><br><span class="line">		<span class="keyword">return</span> <span class="string">"true"</span></span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="string">"false"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>FormatFloat</code>内部实现：<br>可以看到源码注释很详细：需要4个参数分别是：<ul>
<li>f : 要转换的浮点数</li>
<li>fmt : 格式标记(b、e、E、f、g、G)</li>
<li>prec : 精度(数字部分的长度，不包括指数部分)</li>
<li>bitSize : 指定浮点类型(32:float32、64:float64)</li>
</ul>
</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// FormatFloat converts the floating-point number f to a string,</span></span><br><span class="line"><span class="comment">// according to the format fmt and precision prec. It rounds the</span></span><br><span class="line"><span class="comment">// result assuming that the original was obtained from a floating-point</span></span><br><span class="line"><span class="comment">// value of bitSize bits (32 for float32, 64 for float64).</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// The format fmt is one of (格式标记)</span></span><br><span class="line"><span class="comment">// 'b' (-ddddp±ddd, a binary exponent),</span></span><br><span class="line"><span class="comment">// 'e' (-d.dddde±dd, a decimal exponent),</span></span><br><span class="line"><span class="comment">// 'E' (-d.ddddE±dd, a decimal exponent),</span></span><br><span class="line"><span class="comment">// 'f' (-ddd.dddd, no exponent),</span></span><br><span class="line"><span class="comment">// 'g' ('e' for large exponents, 'f' otherwise), or</span></span><br><span class="line"><span class="comment">// 'G' ('E' for large exponents, 'f' otherwise).</span></span><br><span class="line"><span class="comment">//</span></span><br><span class="line"><span class="comment">// The precision prec controls the number of digits</span></span><br><span class="line"><span class="comment">// (excluding the exponent) printed by the 'e', 'E', 'f', 'g', and 'G' formats.</span></span><br><span class="line"><span class="comment">// For 'e', 'E', and 'f' it is the number of digits after the decimal point.</span></span><br><span class="line"><span class="comment">// For 'g' and 'G' it is the total number of digits.</span></span><br><span class="line"><span class="comment">// The special precision -1 uses the smallest number of digits</span></span><br><span class="line"><span class="comment">// necessary such that ParseFloat will return f exactly.</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">FormatFloat</span><span class="params">(f <span class="keyword">float64</span>, fmt <span class="keyword">byte</span>, prec, bitSize <span class="keyword">int</span>)</span> <span class="title">string</span></span> &#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">string</span>(genericFtoa(<span class="built_in">make</span>([]<span class="keyword">byte</span>, <span class="number">0</span>, max(prec+<span class="number">4</span>, <span class="number">24</span>)), f, fmt, prec, bitSize))</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ul>
<li><code>FormatInt</code>内部实现:<br>可以看到第二个参数<code>base</code>表示进制，调用了<code>formatBits</code>这个函数对int进行了转换</li>
</ul>
<figure class="highlight golang"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// FormatInt returns the string representation of i in the given base,</span></span><br><span class="line"><span class="comment">// for 2 &lt;= base &lt;= 36. The result uses the lower-case letters 'a' to 'z'</span></span><br><span class="line"><span class="comment">// for digit values &gt;= 10.</span></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">FormatInt</span><span class="params">(i <span class="keyword">int64</span>, base <span class="keyword">int</span>)</span> <span class="title">string</span></span> &#123;</span><br><span class="line">	_, s := formatBits(<span class="literal">nil</span>, <span class="keyword">uint64</span>(i), base, i &lt; <span class="number">0</span>, <span class="literal">false</span>)</span><br><span class="line">	<span class="keyword">return</span> s</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    <footer class="entry-meta entry-footer">
      
	<span class="ico-folder"></span>
    <a class="article-category-link" href="/categories/Golang/">Golang</a>

      
  <span class="ico-tags"></span>
  <ul class="article-tag-list"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/tags/Golang入门/">Golang入门</a></li></ul>

      
        <div id="donation_div"></div>

<script src="/js/vdonate.js"></script>
<script>
var a = new Donate({
  title: '如果觉得我的文章对您有用，请随意打赏。您的支持将鼓励我继续创作!', // 可选参数，打赏标题
  btnText: 'Donate', // 可选参数，打赏按钮文字
  el: document.getElementById('donation_div'),
  wechatImage: '/css/images/wechatPay.png',
  alipayImage: '/css/images/alipay.jpg'
});
</script>
      

      
        
	<section id="comments" class="comment">
	  <div id="disqus_thread">
	  <noscript>Please enable JavaScript to view the <a href="//disqus.com/?ref_noscript">comments powered by Disqus.</a></noscript>
	  </div>
	</section>

	<script type="text/javascript">
	var disqus_shortname = 'haijdblog';
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/embed.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	(function(){
	  var dsq = document.createElement('script');
	  dsq.type = 'text/javascript';
	  dsq.async = true;
	  dsq.src = '//' + disqus_shortname + '.disqus.com/count.js';
	  (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq);
	}());
	</script>


      
    </footer>
  </div>
  
    
<nav id="article-nav">
  
    <a href="/2017/10/14/GO标准库笔记Ⅰ-IO/" id="article-nav-newer" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Newer</strong>
      <div class="article-nav-title">
        
          Go标准库笔记Ⅰ：IO
        
      </div>
    </a>
  
  
    <a href="/2017/08/23/Go标准库-fmt/" id="article-nav-older" class="article-nav-link-wrap">
      <strong class="article-nav-caption">Older</strong>
      <div class="article-nav-title">Go语言标准库-fmt</div>
    </a>
  
</nav>

  
</article>

<!-- Table of Contents -->

  <aside id="sidebar">
    <div id="toc" class="toc-article">
    <strong class="toc-title">Contents</strong>
    
      <ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#strings库常见例子"><span class="nav-number">1.</span> <span class="nav-text">strings库常见例子</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#strings-Contains-包含"><span class="nav-number">1.1.</span> <span class="nav-text">strings.Contains()包含</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#strings-Index-索引"><span class="nav-number">1.2.</span> <span class="nav-text">strings.Index()索引</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#strings-Split-切割"><span class="nav-number">1.3.</span> <span class="nav-text">strings.Split()切割</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#strings-Join-合并"><span class="nav-number">1.4.</span> <span class="nav-text">strings.Join()合并</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#strings-HasPrefix-strings-HasSuffix-是否包含前、后缀"><span class="nav-number">1.5.</span> <span class="nav-text">strings.HasPrefix() strings.HasSuffix()是否包含前、后缀</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#strconv库常用操作"><span class="nav-number">2.</span> <span class="nav-text">strconv库常用操作</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#Itoa数字转字符串"><span class="nav-number">2.1.</span> <span class="nav-text">Itoa数字转字符串</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Atoi字符串转数字"><span class="nav-number">2.2.</span> <span class="nav-text">Atoi字符串转数字</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ParseBool字符串转bool类型"><span class="nav-number">2.3.</span> <span class="nav-text">ParseBool字符串转bool类型</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ParseFloat字符串转浮点数"><span class="nav-number">2.4.</span> <span class="nav-text">ParseFloat字符串转浮点数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Format-格式化"><span class="nav-number">2.5.</span> <span class="nav-text">Format...格式化</span></a></li></ol></li></ol>
    
    </div>
  </aside>
</section>
        
      </div>
      <footer id="footer" class="site-footer">
  

  <div class="clearfix container">
      <div class="site-info">
	      &copy; 2018 haijd All Rights Reserved.
          
            <span id="busuanzi_container_site_uv">
              本站访客数<span id="busuanzi_value_site_uv"></span>人次  
              本站总访问量<span id="busuanzi_value_site_pv"></span>次
            </span>
          
      </div>
      <div class="site-credit">
        Theme by <a href="https://github.com/iTimeTraveler/hexo-theme-hiero" target="_blank">hiero</a>
      </div>
  </div>
</footer>


<!-- min height -->

<script>
    var contentdiv = document.getElementById("content");

    contentdiv.style.minHeight = document.body.offsetHeight - document.getElementById("allheader").offsetHeight - document.getElementById("footer").offsetHeight + "px";
</script>
    </div>
    <!-- <nav id="mobile-nav">
  
    <a href="/" class="mobile-nav-link">Home</a>
  
    <a href="/archives" class="mobile-nav-link">Archives</a>
  
    <a href="/categories" class="mobile-nav-link">Categories</a>
  
    <a href="/tags" class="mobile-nav-link">Tags</a>
  
    <a href="/about" class="mobile-nav-link">About</a>
  
</nav> -->
    

<!-- mathjax config similar to math.stackexchange -->

<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {
      inlineMath: [ ['$','$'], ["\\(","\\)"] ],
      processEscapes: true
    }
  });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre', 'code']
      }
    });
</script>

<script type="text/x-mathjax-config">
    MathJax.Hub.Queue(function() {
        var all = MathJax.Hub.getAllJax(), i;
        for(i=0; i < all.length; i += 1) {
            all[i].SourceElement().parentNode.className += ' has-jax';
        }
    });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>


  <link rel="stylesheet" href="/fancybox/jquery.fancybox.css">
  <script src="/fancybox/jquery.fancybox.pack.js"></script>


<script src="/js/scripts.js"></script>
<script src="/js/bootstrap.js"></script>
<script src="/js/main.js"></script>








	<script async src="//dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js">
	</script>






  </div>

  <a id="rocket" href="#top" class=""></a>
  <script type="text/javascript" src="/js/totop.js" async=""></script>
</body>
</html>
